import React, { useState, useEffect } from "react";
import {
    Modal,
    ModalContent,
    ModalHeader,
    ModalBody,
    ModalFooter,
    Button,
    Input,
    Checkbox,
    Chip,
    Card,
    CardBody,
    Divider,
    Pagination,
    Spinner,
    Switch,
    Tooltip,
    useDisclosure
} from "@nextui-org/react";
import { SearchIcon } from "@nextui-org/shared-icons";
import { useRouter } from "next/navigation";
import { BiChip, BiFilterAlt, BiReset } from "react-icons/bi";
import ToastUtil from "@/app/utils/toastUtil";
import { searchNotesWithMysql, searchNotesWithES, SearchParams } from "@/app/service/AdvancedSearchService";

interface SearchModalProps {
    isOpen: boolean;
    onOpenChange: (open: boolean) => void;
    initialKeyword?: string;
}

export default function SearchModal({ isOpen, onOpenChange, initialKeyword = "" }: SearchModalProps) {
    const router = useRouter();

    // 搜索参数
    const [keyword, setKeyword] = useState(initialKeyword);
    const [searchContent, setSearchContent] = useState(true);
    const [searchTitle, setSearchTitle] = useState(true);
    const [searchTags, setSearchTags] = useState(false);
    const [includeTags, setIncludeTags] = useState<string[]>([]);
    const [collectionId, setCollectionId] = useState<number | undefined>(undefined);
    const [includePublic, setIncludePublic] = useState(false);
    const [useElasticSearch, setUseElasticSearch] = useState(false);

    // 分页参数
    const [page, setPage] = useState(0);
    const [size, setSize] = useState(10);
    const [total, setTotal] = useState(0);

    // 搜索结果
    const [results, setResults] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [newTagInput, setNewTagInput] = useState("");

    // 搜索历史记录
    const [searchHistory, setSearchHistory] = useState<string[]>([]);

    // 高级搜索选项显示控制
    const [showAdvanced, setShowAdvanced] = useState(false);

    // 常用搜索关键词
    const commonSearchTerms = ["最近更新", "重要", "收藏"];

    // 当模态框打开时，初始化搜索关键词和加载历史记录
    useEffect(() => {
        if (isOpen) {
            if (initialKeyword) {
                setKeyword(initialKeyword);
            }

            // 从localStorage加载搜索历史
            const savedHistory = localStorage.getItem('searchHistory');
            if (savedHistory) {
                try {
                    const parsedHistory = JSON.parse(savedHistory);
                    setSearchHistory(Array.isArray(parsedHistory) ? parsedHistory : []);
                } catch (e) {
                    console.error('Failed to parse search history', e);
                    setSearchHistory([]);
                }
            }
        }
    }, [isOpen, initialKeyword]);

    // 重置所有搜索选项
    const resetFilters = () => {
        setSearchContent(true);
        setSearchTitle(true);
        setSearchTags(false);
        setIncludeTags([]);
        setCollectionId(undefined);
        setIncludePublic(false);
        setUseElasticSearch(false);
        setPage(0);
    };

    // 添加标签
    const addTag = () => {
        if (newTagInput && !includeTags.includes(newTagInput)) {
            setIncludeTags([...includeTags, newTagInput]);
            setNewTagInput("");
        }
    };

    // 移除标签
    const removeTag = (tag: string) => {
        setIncludeTags(includeTags.filter(t => t !== tag));
    };

    // 添加到搜索历史
    const addToSearchHistory = (term: string) => {
        if (!term.trim()) return;

        // 创建新的历史记录数组（最多保存10条）
        const newHistory = [
            term,
            ...searchHistory.filter(item => item !== term) // 移除已存在的相同项
        ].slice(0, 10);

        setSearchHistory(newHistory);

        // 保存到localStorage
        localStorage.setItem('searchHistory', JSON.stringify(newHistory));
    };

    // 从历史记录中移除
    const removeFromHistory = (term: string) => {
        const newHistory = searchHistory.filter(item => item !== term);
        setSearchHistory(newHistory);
        localStorage.setItem('searchHistory', JSON.stringify(newHistory));
    };

    // 清空所有历史记录
    const clearAllHistory = () => {
        setSearchHistory([]);
        localStorage.removeItem('searchHistory');
    };

    // 基本搜索 - 使用现有的FindNoteService
    const basicSearch = async (searchKeyword: string) => {
        try {
            // 使用高级搜索API，但只指定关键词
            const simpleSearchParams: SearchParams = {
                keyword: searchKeyword,
                searchContent: true,  // 默认搜索内容
                searchTitle: true,    // 默认搜索标题
                page: 0,
                size: 20
            };

            // 默认使用MySQL搜索
            const response = await searchNotesWithMysql(simpleSearchParams);

            if (response && response.status) {
                return {
                    data: {
                        records: response.data.records || [],
                        total: response.data.total || 0,
                        current: response.data.current || 1,
                        size: response.data.size || 20
                    }
                };
            }
            return null;
        } catch (error) {
            console.error("搜索出错:", error);
            return null;
        }
    };

    // 高级搜索 - 使用新的搜索API服务
    const advancedSearch = async (params: SearchParams) => {
        try {
            // 使用导入的API服务
            const response = useElasticSearch
                ? await searchNotesWithES(params)
                : await searchNotesWithMysql(params);
            return response;
        } catch (error) {
            console.error("高级搜索出错:", error);
            return null;
        }
    };

    // 执行搜索
    const performSearch = async (searchTerm?: string) => {
        const termToSearch = searchTerm || keyword;

        if (!termToSearch.trim()) {
            ToastUtil("请输入搜索关键词", "ℹ️", "warning");
            return;
        }

        // 添加到搜索历史
        addToSearchHistory(termToSearch);

        // 如果是从历史记录点击的，更新当前输入框
        if (searchTerm) {
            setKeyword(searchTerm);
        }

        setIsLoading(true);

        try {
            let response;

            // 如果显示高级搜索选项，使用高级搜索
            if (showAdvanced) {
                const searchParams: SearchParams = {
                    keyword: termToSearch,
                    searchContent,
                    searchTitle,
                    searchTags,
                    includeTags: includeTags.length > 0 ? includeTags : undefined,
                    collectionId,
                    includePublic,
                    page,
                    size
                };

                response = await advancedSearch(searchParams);
            } else {
                // 否则使用基本搜索
                response = await basicSearch(termToSearch);
            }

            if (response && response.data) {
                setResults(response.data.records || []);
                setTotal(response.data.total || 0);
                if (response.data.records?.length === 0) {
                    ToastUtil("未找到相关笔记", "🔍", "warning");
                } else {
                    ToastUtil(`找到 ${response.data.total} 条结果`, "🎉", "success");
                }
            } else {
                setResults([]);
                setTotal(0);
                ToastUtil("搜索失败，请重试", "❌", "error");
            }
        } catch (error) {
            console.error("搜索出错:", error);
            ToastUtil("搜索出错，请重试", "❌", "error");
            setResults([]);
            setTotal(0);
        } finally {
            setIsLoading(false);
        }
    };

    // 当按下回车时进行搜索
    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === "Enter") {
            performSearch();
        }
    };

    // 点击笔记项跳转到笔记详情
    const handleNoteClick = (noteId: number) => {
        router.push(`/note/${noteId}`);
        onOpenChange(false);
    };

    return (
        <Modal
            isOpen={isOpen}
            onOpenChange={onOpenChange}
            size="3xl"
            scrollBehavior="inside"
            backdrop="blur"
            placement="center"
            classNames={{
                body: "py-4",
                backdrop: "bg-gradient-to-t from-zinc-900/50 to-zinc-900/10",
                base: "border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-xl",
                header: "border-b-1 border-zinc-200 dark:border-zinc-800 px-6 py-4",
                footer: "border-t-1 border-zinc-200 dark:border-zinc-800 px-6 py-4",
                closeButton: "hover:bg-zinc-100 dark:hover:bg-zinc-800 active:bg-zinc-200 dark:active:bg-zinc-700"
            }}
        >
            <ModalContent>
                <>
                    <ModalHeader className="flex gap-1 items-center">
                        <SearchIcon className="text-primary mr-2 text-xl" />
                        <span className="text-xl">高级搜索</span>
                    </ModalHeader>

                    <ModalBody>
                        <div className="space-y-4">
                            {/* 搜索输入框 */}
                            <div className="flex flex-col gap-3">
                                <div className="flex items-center gap-2">
                                    <Input
                                        autoFocus
                                        fullWidth
                                        placeholder="输入关键词搜索..."
                                        value={keyword}
                                        onChange={(e) => setKeyword(e.target.value)}
                                        onKeyDown={handleKeyDown}
                                        size="lg"
                                        radius="lg"
                                        startContent={<SearchIcon className="text-default-400 text-xl" />}
                                        endContent={
                                            <div className="flex items-center gap-1">
                                                {keyword && (
                                                    <Button
                                                        isIconOnly
                                                        size="sm"
                                                        variant="light"
                                                        onPress={() => setKeyword("")}
                                                    >
                                                        <svg
                                                            xmlns="http://www.w3.org/2000/svg"
                                                            fill="none"
                                                            viewBox="0 0 24 24"
                                                            strokeWidth={1.5}
                                                            stroke="currentColor"
                                                            className="w-4 h-4"
                                                        >
                                                            <path
                                                                strokeLinecap="round"
                                                                strokeLinejoin="round"
                                                                d="M6 18L18 6M6 6l12 12"
                                                            />
                                                        </svg>
                                                    </Button>
                                                )}
                                                <Button
                                                    isIconOnly
                                                    size="sm"
                                                    variant={showAdvanced ? "flat" : "light"}
                                                    color={showAdvanced ? "primary" : "default"}
                                                    onClick={() => setShowAdvanced(!showAdvanced)}
                                                    className="ml-1"
                                                >
                                                    <BiFilterAlt className="text-lg" />
                                                </Button>
                                            </div>
                                        }
                                        classNames={{
                                            inputWrapper: "shadow-sm"
                                        }}
                                    />
                                    <Button
                                        color="primary"
                                        onClick={() => performSearch()}
                                        isLoading={isLoading}
                                        size="lg"
                                        radius="lg"
                                        className="px-6"
                                    >
                                        搜索
                                    </Button>
                                </div>

                                {/* 常用选项和历史记录 */}
                                {!showAdvanced && (
                                    <>
                                        {/* 常用搜索词 */}
                                        <div className="flex flex-wrap gap-2 mb-1">
                                            <span className="text-xs text-default-500 self-center pr-2">常用:</span>
                                            {commonSearchTerms.map(term => (
                                                <Chip
                                                    key={term}
                                                    variant="flat"
                                                    color="default"
                                                    className="cursor-pointer opacity-80 hover:opacity-100"
                                                    onClick={() => performSearch(term)}
                                                >
                                                    {term}
                                                </Chip>
                                            ))}
                                        </div>

                                        {/* 历史记录 */}
                                        {searchHistory.length > 0 && (
                                            <div className="flex flex-col gap-1">
                                                <div className="flex justify-between items-center">
                                                    <span className="text-xs text-default-500">历史记录:</span>
                                                    <Button
                                                        size="sm"
                                                        variant="light"
                                                        color="danger"
                                                        className="h-6 min-w-0 p-0 px-2"
                                                        onClick={clearAllHistory}
                                                    >
                                                        清空
                                                    </Button>
                                                </div>
                                                <div className="flex flex-wrap gap-2">
                                                    {searchHistory.map((term, index) => (
                                                        <Chip
                                                            key={`${term}-${index}`}
                                                            variant="bordered"
                                                            color="primary"
                                                            className="cursor-pointer"
                                                            onClose={() => removeFromHistory(term)}
                                                            onClick={() => performSearch(term)}
                                                        >
                                                            {term}
                                                        </Chip>
                                                    ))}
                                                </div>
                                            </div>
                                        )}
                                    </>
                                )}
                            </div>

                            {/* 高级搜索选项 */}
                            {showAdvanced && (
                                <Card shadow="sm" className="border border-neutral-200 dark:border-neutral-800">
                                    <CardBody className="gap-4 p-4">
                                        <div className="flex justify-between items-center">
                                            <h3 className="text-md font-medium flex items-center gap-2">
                                                <BiFilterAlt className="text-primary" />
                                                高级筛选
                                            </h3>
                                            <Button
                                                size="sm"
                                                variant="light"
                                                color="primary"
                                                startContent={<BiReset />}
                                                onClick={resetFilters}
                                                className="min-w-20"
                                            >
                                                重置
                                            </Button>
                                        </div>

                                        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                                            <Checkbox isSelected={searchTitle} onValueChange={setSearchTitle} className="min-w-32">
                                                搜索标题
                                            </Checkbox>
                                            <Checkbox isSelected={searchContent} onValueChange={setSearchContent} className="min-w-32">
                                                搜索内容
                                            </Checkbox>
                                            <Checkbox isSelected={searchTags} onValueChange={setSearchTags} className="min-w-32">
                                                搜索标签
                                            </Checkbox>
                                            <Checkbox isSelected={includePublic} onValueChange={setIncludePublic} className="min-w-32">
                                                包含公开笔记
                                            </Checkbox>
                                        </div>

                                        <Divider />

                                        {/* 标签过滤 */}
                                        <div className="space-y-2">
                                            <h3 className="text-sm font-medium flex items-center gap-2">
                                                <BiChip className="text-primary" />
                                                按标签筛选
                                            </h3>
                                            <div className="flex gap-2 items-center">
                                                <Input
                                                    size="sm"
                                                    placeholder="添加标签..."
                                                    value={newTagInput}
                                                    onChange={(e) => setNewTagInput(e.target.value)}
                                                    onKeyDown={(e) => e.key === "Enter" && addTag()}
                                                    startContent={<BiChip className="text-default-400" />}
                                                    className="flex-1"
                                                />
                                                <Button size="sm" onClick={addTag} color="primary" variant="flat">添加</Button>
                                            </div>

                                            {includeTags.length > 0 && (
                                                <div className="flex flex-wrap gap-2 mt-2">
                                                    {includeTags.map((tag) => (
                                                        <Chip
                                                            key={tag}
                                                            onClose={() => removeTag(tag)}
                                                            variant="flat"
                                                            color="primary"
                                                        >
                                                            {tag}
                                                        </Chip>
                                                    ))}
                                                </div>
                                            )}
                                        </div>

                                        <Divider />

                                        {/* 搜索引擎选择 */}
                                        <div className="flex items-center justify-between">
                                            <div>
                                                <h3 className="text-sm font-medium flex items-center gap-2">
                                                    <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4 text-primary" viewBox="0 0 24 24">
                                                        <path fill="currentColor" d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z" />
                                                    </svg>
                                                    搜索引擎
                                                </h3>
                                                <p className="text-xs text-default-500">选择ElasticSearch可获得更好的搜索体验</p>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <span className={`text-sm ${!useElasticSearch ? 'font-medium text-primary' : 'text-default-500'}`}>MySQL</span>
                                                <Switch
                                                    isSelected={useElasticSearch}
                                                    onValueChange={setUseElasticSearch}
                                                    size="sm"
                                                    color="primary"
                                                />
                                                <span className={`text-sm ${useElasticSearch ? 'font-medium text-primary' : 'text-default-500'}`}>ElasticSearch</span>
                                            </div>
                                        </div>
                                    </CardBody>
                                </Card>
                            )}

                            {/* 搜索结果 */}
                            {isLoading ? (
                                <div className="flex justify-center py-8">
                                    <Spinner color="primary" label="搜索中..." />
                                </div>
                            ) : (
                                results.length > 0 && (
                                    <div className="space-y-4">
                                        {/* 将Chip放在Divider外面，避免hr标签错误 */}
                                        <div className="flex justify-center items-center gap-2 my-4">
                                            <div className="flex-1">
                                                <Divider />
                                            </div>
                                            <Chip size="sm" variant="flat" color="primary" className="px-3">
                                                搜索结果 ({total})
                                            </Chip>
                                            <div className="flex-1">
                                                <Divider />
                                            </div>
                                        </div>

                                        {/* 使用grid布局统一卡片宽度 */}
                                        <div className="grid grid-cols-1 gap-4">
                                            {results.map((note) => (
                                                <Card
                                                    key={note.id || note.noteId}
                                                    isPressable
                                                    onPress={() => handleNoteClick(note.id || note.noteId)}
                                                    className="hover:border-primary-400 transition-colors hover:shadow-md w-full"
                                                    shadow="sm"
                                                >
                                                    <CardBody className="p-4">
                                                        <div className="space-y-3">
                                                            <div className="flex items-center gap-2">
                                                                <h3 className="text-lg font-medium line-clamp-1">
                                                                    {note.title || "无标题笔记"}
                                                                </h3>
                                                                {note.isPublic && (
                                                                    <Chip size="sm" color="success" variant="flat">公开</Chip>
                                                                )}
                                                            </div>

                                                            {/* 内容预览 - 限制为2行 */}
                                                            <p className="text-sm text-default-600 line-clamp-2 min-h-[2.5rem]">
                                                                {note.contentSummary || note.content?.substring(0, 150) || "无内容预览"}
                                                            </p>

                                                            <div className="flex justify-between items-center pt-1">
                                                                <div className="flex gap-1 flex-wrap max-w-[70%]">
                                                                    {note.tags && note.tags.length > 0 ? note.tags.map((tag: string, index: number) => (
                                                                        <Chip key={index} size="sm" variant="flat" color="primary" className="max-w-[120px]">
                                                                            <span className="truncate">{tag}</span>
                                                                        </Chip>
                                                                    )) : (
                                                                        <span className="text-xs text-default-400">无标签</span>
                                                                    )}
                                                                </div>
                                                                <div className="text-xs text-default-500">
                                                                    {note.updateTime || note.updatedAt || note.createTime || note.createdAt || "未知时间"}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </CardBody>
                                                </Card>
                                            ))}
                                        </div>

                                        {/* 分页 - 只在高级搜索模式下显示 */}
                                        {showAdvanced && total > size && (
                                            <div className="flex justify-center mt-6">
                                                <Pagination
                                                    total={Math.ceil(total / size)}
                                                    initialPage={page + 1}
                                                    page={page + 1}
                                                    onChange={(p) => setPage(p - 1)}
                                                    color="primary"
                                                    size="sm"
                                                    showControls
                                                    classNames={{
                                                        cursor: "shadow-md",
                                                    }}
                                                />
                                            </div>
                                        )}
                                    </div>
                                )
                            )}
                        </div>
                    </ModalBody>

                    <ModalFooter>
                        <Button variant="light" onPress={() => onOpenChange(false)}>
                            关闭
                        </Button>
                        {results.length > 0 && (
                            <Button
                                color="primary"
                                variant="flat"
                                onPress={() => window.print()}
                                startContent={
                                    <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24">
                                        <path fill="currentColor" d="M19 8h-1V3H6v5H5c-1.7 0-3 1.3-3 3v5h4v4h12v-4h4v-5c0-1.7-1.3-3-3-3M8 5h8v3H8V5m8 12v2H8v-4h8v2zm2-2v-2H6v2H4v-3c0-.6.4-1 1-1h14c.6 0 1 .4 1 1v3h-2z" />
                                    </svg>
                                }
                            >
                                打印结果
                            </Button>
                        )}
                    </ModalFooter>
                </>
            </ModalContent>
        </Modal>
    );
} 